<!--
 * @Author: Liz.Zheng
 * @Date: 2021-12-03 10:09:27
 * @LastEditTime: 2023-02-22 15:03:33
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 基本信息
 * @Motto: Write the code. Change the world.
-->
<template>
  <div class="basic-info">
    <a-form layout="vertical">
      <a-row :gutter="12">
        <a-col :span="12">
          <a-card title="基本信息">
            <a-row :gutter="12" :wrap="true">
              <a-col :span="8">
                <a-form-item
                  label="模板选择"
                  v-bind="validateInfos.template_id"
                >
                  <a-select
                    v-model:value="formData.template_id"
                    placeholder="请选择"
                    :options="templateList"
                    :fieldNames="{
                      label: 'template_name',
                      value: 'id',
                    }"
                    @select="handleTemplateSelect"
                  >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="合同编号"
                  v-bind="validateInfos.contract_number"
                >
                  <a-input
                    placeholder="请输入"
                    v-model:value="formData.contract_number"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="经办人" v-bind="validateInfos.followup_uid">
                  <a-select
                    show-search
                    v-model:value="formData.followup_uid"
                    placeholder="请选择"
                    :filter-option="filterOption"
                  >
                    <a-select-option
                      v-for="item of optionData.followup"
                      :value="item.uid"
                      :key="item.uid"
                      :label="item.realname"
                      >{{ item.realname }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="签订日" v-bind="validateInfos.sign_time">
                  <a-date-picker
                    class="w-100p"
                    v-model:value="formData.sign_time"
                    :valueFormat="dateFormatStr"
                    :allowClear="false"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="合同开始日期"
                  v-bind="validateInfos.lease_starttime"
                >
                  <a-date-picker
                    class="w-100p"
                    v-model:value="formData.lease_starttime"
                    :valueFormat="dateFormatStr"
                    @change="(val) => handleLeaseTimeChange(val, 'start')"
                    :allowClear="false"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="合同结束日期"
                  v-bind="validateInfos.lease_endtime"
                >
                  <a-date-picker
                    class="w-100p"
                    v-model:value="formData.lease_endtime"
                    :valueFormat="dateFormatStr"
                    @change="(val) => handleLeaseTimeChange(val, 'end')"
                    :allowClear="false"
                  />
                </a-form-item>
              </a-col>
              <!-- <a-col :span="16">
                <a-form-item
                  label="租赁起始日期"
                  v-bind="validateInfos.lease_time"
                >
                  <a-range-picker
                    class="w-100p"
                    v-model:value="formData.lease_time"
                    :valueFormat="dateFormatStr"
                    :disabled-date="disabledDate"
                    @change="handleLeaseTimeChange"
                  />
                </a-form-item>
              </a-col> -->
              <!-- <a-col :span="8">
                <a-form-item label="租赁数量">
                  <a-input
                    placeholder="请输入"
                    v-model:value="leaseArea"
                    style="width: 60%"
                    :disabled="true"
                  />
                  <a-select
                    v-model:value="areaUnit"
                    style="width: 35%; margin-left: 5%"
                    :disabled="true"
                  >
                    <a-select-option
                      v-for="item of optionData.lease_square_unit"
                      :value="item.key"
                      :key="item.key"
                      >{{ item.name }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-item
                  label="单价保留小数点"
                  v-bind="validateInfos.unit_price_point"
                >
                  <a-input-group compact>
                    <a-input-number
                      placeholder="请输入"
                      v-model:value="formData.unit_price_point"
                      :min="0"
                    />
                    <span class="num-input-suffix">位</span>
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="计算精度"
                  v-bind="validateInfos.calculate_accuracy"
                >
                  <a-select
                    v-model:value="formData.calculate_accuracy"
                    placeholder="请选择"
                  >
                    <a-select-option
                      v-for="item of optionData.calculate_accuracy_unit"
                      :value="item.key"
                      :key="item.key"
                      >{{ item.name }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="计算顺序"
                  v-bind="validateInfos.calculate_order"
                >
                  <a-select
                    v-model:value="formData.calculate_order"
                    placeholder="请选择"
                  >
                    <a-select-option
                      v-for="item of optionData.calculate_order_unit"
                      :value="item.key"
                      :key="item.key"
                      >{{ item.name }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="应收整数（四舍五入）"
                  v-bind="validateInfos.receivable_round"
                >
                  <a-select
                    v-model:value="formData.receivable_round"
                    placeholder="请选择"
                  >
                    <a-select-option
                      v-for="item of optionData.receivable_round_unit"
                      :value="item.key"
                      :key="item.key"
                      >{{ item.name }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item  v-bind="validateInfos.org_branch_id">
                  <template #label>
                    <span style="margin-right: 6px;">所属公司</span>
                    <a-tooltip>
                      <template #title >
                        如果选择了所属公司，则该合同这是以该公司身份签署，不选择则以总公司身份签署。
                      </template >
                      <span><QuestionCircleOutlined /></span>
                    </a-tooltip>
                  </template>
                  <a-select
                    v-model:value="formData.org_branch_id"
                    :fieldNames="{
                      label: 'company',
                      value: 'id',
                    }"
                    :options="companyList"
                    placeholder="请选择"
                    @change="changebranchid"
                  />
                </a-form-item>
              </a-col>
<!--              <a-col :span="8">-->
<!--                <a-form-item>-->
<!--                  <template #label>-->
<!--                    签署公司账户收付款-->
<!--                    <TextTip-->
<!--                      tips="启用指定公司账户收付款，则该合同下的所有的账单使用该公司的收支账户"-->
<!--                    />-->
<!--                  </template>-->
<!--                  <a-select-->
<!--                    v-model:value="formData.is_branch_account"-->
<!--                    placeholder="请选择"-->
<!--                  >-->
<!--                    <a-select-option-->
<!--                      :value="1"-->
<!--                      :key="1"-->
<!--                    >是</a-select-option>-->
<!--                    <a-select-option-->
<!--                      :value="0"-->
<!--                      :key="0"-->
<!--                    >否</a-select-option>-->
<!--                  </a-select>-->
<!--                </a-form-item>-->
<!--              </a-col>-->
            </a-row>
          </a-card>
          <a-card class="mt-10" v-if="isCostContract">
            <template #title>
              <span>业主信息</span>
              <span style="color: red; font-size: 12px; margin-left: 4px">
                {{proprietorErrorMsg}}
              </span>
            </template>
            <a-row :gutter="12" :wrap="true">
              <a-col :span="8">
                <a-form-item label="业主" v-bind="validateInfos.proprietor_id">
                  <a-select
                    v-model:value="formData.proprietor_id"
                    show-search
                    placeholder="请选择绑定业主的房间"
                    :disabled="true"
                    :options="proprietorList"
                  >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="业主联系人"
                  v-bind="validateInfos.proprietor_link_name"
                >
                  <a-input
                    placeholder="请输入业主联系人姓名"
                    v-model:value="formData.proprietor_info.link_name"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="业主手机号"
                  v-bind="validateInfos.proprietor_link_phone"
                >
                  <a-input
                    placeholder="请输入业主手机号"
                    v-model:value="formData.proprietor_info.phone"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
          <a-card class="mt-10" title="租客信息" v-else>
            <a-row :gutter="12" :wrap="true">
              <a-col :span="8">
                <a-form-item label="租客" v-bind="validateInfos.owner_id">
                  <TenantComponent
                      :ownerId="formData.owner_id"
                      :titleser="'选择租客'"
                      @selectcancel="Selectcancel"
                      @request="$utils.commonRequest"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="行业"
                  v-bind="validateInfos['owner_info.industry_id']"
                >
                  <a-select
                    v-model:value="formData.owner_info.industry_id"
                    placeholder="请选择"
                    :disabled="isRenewal"
                  >
                    <a-select-option
                      v-for="item of optionData.all_industry"
                      :value="item.id"
                      :key="item.id"
                      >{{ item.name }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="法人"
                  v-bind="validateInfos['owner_info.corporation']"
                >
                  <a-input
                    placeholder="请输入名称"
                    :disabled="isRenewal"
                    v-model:value="formData.owner_info.corporation"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="签订人"
                  v-bind="validateInfos['owner_info.signatory']"
                >
                  <a-input
                    placeholder="请输入名称"
                    v-model:value="formData.owner_info.signatory"
                    :disabled="signatoryDisabled || isRenewal"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
          <a-card class="mt-10" title="意向信息" v-if="isPurposeContract">
            <a-row :gutter="12" :wrap="true">
              <a-col :span="8">
                <a-form-item
                  label="意向金应付金额"
                  v-bind="validateInfos.purpose_receive_price"
                >
                  <a-input-number
                    placeholder="请输入"
                    v-model:value="formData.purpose_receive_price"
                    :min="0"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="意向金应付日期"
                  v-bind="validateInfos.purpose_receive_time"
                >
                  <a-date-picker
                    class="w-100p"
                    v-model:value="formData.purpose_receive_time"
                    :valueFormat="dateFormatStr"
                    @change="(val) => handleLeaseTimeChange(val, 'start')"
                    :allowClear="false"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="意向房屋锁定终止日期"
                  v-bind="validateInfos.purpose_unlock_time"
                >
                  <a-date-picker
                    class="w-100p"
                    v-model:value="formData.purpose_unlock_time"
                    :valueFormat="dateFormatStr"
                    @change="(val) => handleLeaseTimeChange(val, 'start')"
                    :allowClear="false"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="意向金支付方式"
                  v-bind="validateInfos.purpose_pay_method"
                >
                  <a-select
                    v-model:value="formData.purpose_pay_method"
                    placeholder="请选择"
                  >
                    <a-select-option
                      v-for="item of optionData.purposePayMethod"
                      :value="item.key"
                      :key="item.key"
                      >{{ item.name }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  v-bind="validateInfos.purpose_is_return"
                >
                  <template #label>
                    <span style="margin-right: 6px;">意向金类型</span>
                    <a-tooltip>
                      <template #title >
                        意向金表示可退，定金表示不可退。
                      </template >
                      <span><QuestionCircleOutlined /></span>
                    </a-tooltip>
                  </template>
                  <a-select
                    v-model:value="formData.purpose_is_return"
                    placeholder="请选择"
                  >
                    <a-select-option
                      v-for="item of optionData.purpose_is_return"
                      :value="item.key"
                      :key="item.key"
                      >{{ item.name }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
          <a-card class="mt-10" title="滞纳金" v-if="!isCostContract">
            <a-row :gutter="12" :wrap="true">
              <a-col :span="8">
                <a-form-item v-bind="validateInfos['late_fee.startDay']">
                  <template #label>
                    <a-space :size="4">
                      <span>起算天数 </span>
                      <a-tooltip>
                        <template #title>若填写0，则不计算滞纳金。</template>
                        <question-circle-outlined />
                      </a-tooltip>
                    </a-space>
                  </template>
                  <a-input-group compact>
                    <a-input-number
                      placeholder="请输入"
                      v-model:value="formData.late_fee.startDay"
                      :min="0"
                    />
                    <span class="num-input-suffix">天</span>
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="滞纳金比例"
                  v-bind="validateInfos['late_fee.ratio']"
                >
                  <a-input-group compact>
                    <a-input-number
                      placeholder="请输入"
                      v-model:value="formData.late_fee.ratio"
                      :min="0"
                    />
                    <span class="num-input-suffix">%/天</span>
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item v-bind="validateInfos['late_fee.toplimit']">
                  <template #label>
                    <a-space :size="4">
                      <span>滞纳金上限</span>
                      <a-tooltip>
                        <template #title>若填写0，则无上限限制。</template>
                        <question-circle-outlined />
                      </a-tooltip>
                    </a-space>
                  </template>
                  <a-input-number
                    placeholder="请输入"
                    v-model:value="formData.late_fee.toplimit"
                    :min="0"
                  />
                  <span class="num-input-suffix">%</span>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-col>
        <a-col :span="12" class="building">
          <a-spin :spinning="chooseRoomLoading">
            <a-card
              :bodyStyle="{
              height:  isCostContract ? '595px' : '900px',
              overflow: 'hidden',
            }"
              :title="houseCardTitle"
            >
              <template #extra>
                <a-button
                  type="link"
                  @click="changeHouseCard"
                  v-if="roomList.length"
                >
                  {{ showSelectedHouse ? "选择房源" : "查看已选" }}
                </a-button>
              </template>
              <template v-if="showHousingResources">
                <ChooseHousingResources
                  v-show="!showSelectedHouse"
                  alertTip="请先选择合同模板再选择房源"
                  :defaultChecked="{ roomList }"
                  :defaultCheckedIds="defaultCheckedIds"
                  :getShowList="showAllList"
                  :areaEmptyDisabled="!isCostContract"
                  :showList="currentProjectBuild"
                  limitType="village"
                  :disableBuildCheck="true"
                  :includeAreaRoom="room_rent"
                  @request="$utils.commonRequest"
                  @getResult="getRoomList"
                  :clauseType="clauseType"
                  @changeTreeLoading="changeTreeLoading"
                />
                <CheckedHousingResources
                  v-show="showSelectedHouse"
                  :houseList="roomList"
                  :maxTotal="isCostContract"
                  :includeSelfArea="includeSelfArea"
                />
              </template>
            </a-card>
          </a-spin>
        </a-col>
      </a-row>
      <a-row class="mt-20">
        <a-card class="w-100p" title="合同标签">
          <template #extra>
            <a-button type="primary" ghost @click="tagAddVisible = true">
              标签管理
            </a-button>
          </template>
          <template v-if="contractTagList.length">
            <tag-list :list="contractTagList" @check="handleTagCheck" />
          </template>
          <a-empty v-else description="您还没有添加合同标签哦~" />
        </a-card>
      </a-row>

      <a-row class="mt-20">
        <a-card class="w-100p" title="拓展字段">
          <template #extra>
            <a-button type="primary" ghost @click="extraManageVisible = true">
              字段管理
            </a-button>
          </template>
          <template v-if="formData?.extra_field?.length">
            <a-row :gutter="12" :wrap="true">
              <a-col
                :span="6"
                v-for="(extraItem, index) in formData.extra_field"
                :key="index"
              >
                <a-form-item :label="extraItem.name">
                  <a-input
                    placeholder="请输入"
                    v-model:value="extraItem.value"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </template>
          <a-empty v-else description="您还没有添加拓展字段哦~" />
        </a-card>
      </a-row>
      <!-- <a-row class="mt-20">
        <a-card class="w-100p" title="自定义字段"></a-card>
      </a-row> -->
    </a-form>
    <TagAdd
      :visible="tagAddVisible"
      @cancel="tagAddVisible = false"
      @success="handleTagAddSuccess"
      title="合同标签"
      :requestUrl="{
        color: '/manage/taglib/contract/color',
        save: '/manage/taglib/contract',
        detail: '/manage/taglib/contract/get',
      }"
    />

    <!--  拓展字段管理   -->
    <ExtraManage :visible="extraManageVisible" @closeModal="closeExtraManage" />
  </div>
</template>

<script>
import moment from "moment";
import {
  computed,
  defineComponent,
  reactive,
  ref,
  watch,
  toRefs,
  createVNode,
  toRaw,
  nextTick,
  watchEffect,
  onMounted,
} from "vue";
import {
  CheckedHousingResources,
  ChooseHousingResources,
  TextTip,
} from "bl-common-vue3";
// import ChooseHousingResources from "./ChooseHousingResources/index.vue";
import TagList from "../../../components/Tag/show.vue";
import { Form, message, Modal, notification } from "ant-design-vue";
import store from "../../../store";
import request from "../../../common/utils/request";
import {
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
  DiffFilled
} from "@ant-design/icons-vue";
import OwnerContEdit from "../../village/OwnerManage/modules/OwnerContEdit.vue";
import TagAdd from "../../../components/Tag/add.vue";
import { useRoute, useRouter } from "vue-router";
import _ from "lodash";
import ExtraManage from "@/views/contract/NewContract/modules/ExtraManage.vue";
import utils from "@/common/utils/utils";
import { TenantComponent } from "bl-common-vue3";
const useForm = Form.useForm;

export default defineComponent({
  name: "ContractBasicInfo",
  props: {
    detailDataByPort: {
      type: Object,
      default: () => {
        return {};
      },
    }
  },
  components: {
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
    ChooseHousingResources,
    CheckedHousingResources,
    TagList,
    TagAdd,
    OwnerContEdit,
    ExtraManage,
    QuestionCircleOutlined,
    TextTip,
    DiffFilled,
    TenantComponent,
  },
  setup(props, context) {
    const $route = useRoute();
    const $router = useRouter();
    const isRenewal = computed(
      () => $route.query.editType == "renewal"
    );

    // 是否变更合同
    const isChangeContract = computed(
      () => $route.query.contractEditType == "change"
    );

    // 是否意向变更合同
    const isPurposeChangeContract = computed(
      () => $route.query.contractType == "purposeContractChange"
    );

    // 是否复制合同
    const isCopyContract = computed(
      () => $route.query.contractEditType == "copy"
    );

    const includeSelfArea = computed(
      () => isRenewal.value || isChangeContract.value || isPurposeChangeContract.value
    );
    // 是否成本合同
    const isCostContract = computed(
      () => $route.query.contractType == "costContract"
    );

    const dateFormatStr = "YYYY-MM-DD";
    const today = moment().format(dateFormatStr);
    const todayAfterYear = moment()
      .add(1, "years")
      .subtract(1, "days")
      .format(dateFormatStr);
    const contractDateRange = computed(() => store.getters.contractDateRange);
    const disabledDate = (current) => {
      const { startDate, endDate } = contractDateRange.value;
      return (
        current < moment(startDate).startOf("day") ||
        current > moment(endDate).endOf("days")
      );
    };

    // 是否意向合同 或者意向合同变更
    const isPurposeContract = computed(
      () => $route.query.contractType == "purposeContract" || $route.query.contractType == "purposeContractChange" || $route.query.contractType == "purposeContractEdit"
    );

    // 是否意向合同转正
    const isTransferNormal = computed(
      () => $route.query.editType == "transferNormal"
    );

    const state = reactive({
      formData: {
        //   默认合同模板id
        template_id: undefined,
        //   合同编号
        contract_number: "",
        // 经办人uid
        followup_uid: "",
        // 合同签订时间
        sign_time: today,
        // 租赁起始时间
        // lease_time: [today, todayAfterYear],
        lease_starttime: today,
        lease_endtime: todayAfterYear,
        // 单价保留小数点
        unit_price_point: 2,
        // 计算精度
        calculate_accuracy: "",
        // 计算顺序
        calculate_order: "",
        // 应收整数
        receivable_round: 0,
        // 租客信息
        owner_id: undefined,
        owner_info: {
          owner_id: "",
          owner_name: "",
          industry_id: undefined,
          corporation: "",
          signatory: "",
        },
        // 滞纳金
        late_fee: {
          startDay: "",
          ratio: "",
          toplimit: "",
        },
        // 业主信息
        proprietor_id: undefined,
        proprietor_info: {
          id: null,
          name: "",
          link_name: "",
          phone: "",
          is_new: 1,
        },

        // 意向信息
        purpose_receive_price: null,
        purpose_receive_time: null,
        purpose_unlock_time: null,
        purpose_pay_method: null,
        purpose_is_return: null,
        // 自定义字段
        extra_field: [],
        // 分公司
        org_branch_id: undefined,
        is_branch_account: 1,
      },
      extraManageVisible: false, // 拓展字段管理
      rulesData: {
        template_id: [{ required: true, message: "必选" }],
        contract_number: [{ required: true, message: "必填" }],
        followup_uid: [{ required: true, message: "必选" }],
        sign_time: [{ required: true, message: "必选" }],
        lease_starttime: [{ required: true, message: "必选" }],
        lease_endtime: [{ required: true, message: "必选" }],
        unit_price_point: [{ required: true, message: "必选" }],
        calculate_accuracy: [{ required: true, message: "必选" }],
        calculate_order: [{ required: true, message: "必选" }],
        receivable_round: [{ required: true, message: "必选" }],
        org_branch_id:[{ required: true, message: "必选" }],
        owner_id: [
          {
            required: isCostContract.value ? false : true,
            message: "必选",
          },
        ],
        proprietor_id: [
          {
            required: isCostContract.value ? true : false,
            message: "必选",
          },
        ],
        // 意向信息
        purpose_receive_price: [
          {
            required: isPurposeContract.value ? true : false,
            message: "必填",
          },
        ],
        purpose_receive_time: [
          {
            required: isPurposeContract.value ? true : false,
            message: "必选",
          },
        ],
        purpose_unlock_time: [
          {
            required: isPurposeContract.value ? true : false,
            message: "必选",
          },
        ],
        purpose_pay_method: [
          {
            required: isPurposeContract.value ? true : false,
            message: "必选",
          },
        ],
        purpose_is_return: [
          {
            required: isPurposeContract.value ? true : false,
            message: "必选",
          },
        ],
      },
      optionData: {},
      areaUnit: "",
      areaUnitName: "",
      leaseArea: 0,
      signatoryDisabled: true,
      showSelectedHouse: false, // 展示已选房源
      roomList: [],
      defaultCheckedIds: {
        villageId: $route.query.village_id || 0,
        buildId: $route.query.build_id || 0,
        layerId: $route.query.layer_id || 0,
        roomId: $route.query.room_id || 0,
        subRoomId: $route.query.sub_room_id || 0,
      },
      validTime: {},
      showAllList: 0,
      currentProjectBuild: {},

      clauseType: "lease", //条款类型
      showHousingResources: true,

      companyList: [],
      defaultFinish: false,
      housedata:{},
      chooseRoomLoading: false,
      proprietorErrorMsg: '',
    });

    const houseCardTitle = computed(() =>
      state.showSelectedHouse ? "已选房源" : "请勾选房源"
    );

    const changeHouseCard = () => {
      state.showSelectedHouse = !state.showSelectedHouse;
    };

    const { resetFields, validate, validateInfos } = useForm(
      state.formData,
      state.rulesData
    );

    const getRoomList = (result) => {
      state.roomList = result.roomList;
      context.emit("changeroomList", state.roomList);
      if (isCostContract.value) {
        // 如果是成本合同 需要 请求 业主列表信息 （目前成本合同 只有 新增）
        getProprietorList(state.roomList);
      }
    };

    const changeTreeLoading = (val) => {
      context.emit("changeTreeLoading", val);
    };

    const validateForm = () => {
      validate()
        .then(async () => {
          if (!state.roomList.length) {
            message.warning("请选择有可租面积的房源~");
            context.emit("fail", { key: "basicInfo" });
            return;
          }
          store.dispatch("SetCheckedRoomList", state.roomList);
          context.emit("changeroomList", state.roomList);
          store.dispatch("SetContractDateRange", {
            startDate: state.formData.lease_starttime,
            endDate: state.formData.lease_endtime,
          });
          const currentTemplate = templateList.value.find(
            (item) => item.id == state.formData.template_id
          );
          let params = {};
          store.dispatch("SetDefaultClause", currentTemplate).then(() => {
            params = JSON.parse(JSON.stringify(state.formData));
            let lease_square = [];
            let property_square = [];
            let build_bind = { room: [], build: [] };
            state.roomList.forEach((item) => {
              let obj = {
                id: item.id,
                room_number: item.room_number,
                room_name: item.room_name,
                showArea: item.showArea,
              };
              if (item.extra) {
                obj = {
                  ...obj,
                  ...item.extra,
                  extra: item.extra,
                };
              } else {
                obj = {
                  ...obj,
                  layer_id: item.layer_id,
                  layer_number: item.layer_number,
                  layer_name: item.layer_name,
                };
              }

              let lease_area = (
                Number(item.rental_area) -
                Number(item.rent_area ? item.rent_area.lease_square : 0)
              ).toFixed(2);
              let charging_area = (
                Number(item.charging_area) -
                Number(item.rent_area ? item.rent_area.property_square : 0)
              ).toFixed(2);
              if (isRenewal.value) {
                // 续租 面积为之前的面积
                let originalLease = props.detailDataByPort?.lease_square || [];
                let originalProperty = props.detailDataByPort?.property_square || [];
                let originalLeaseArea = originalLease.find((v) => v.id == item.id)?.lease_area;
                let originalPropertyArea = originalProperty.find((v) => v.id == item.id)?.lease_area;
                if (originalLeaseArea) {
                  lease_area = originalLeaseArea;
                }
                if (originalPropertyArea) {
                  charging_area = originalPropertyArea;
                }
              }
              lease_square.push({
                ...obj,
                lease_area,
              });
              property_square.push({
                ...obj,
                lease_area: charging_area,
              });
              build_bind.room.push({
                ...obj,
                rental_area: item.rental_area,
                charging_area: item.charging_area,
                rent_area: item.rent_area,
                is_unreal: item?.is_unreal || 0,
                lease_square: state.areaUnit,
                lease_square_text: state.areaUnitName,
              });
              const idx = build_bind.build.findIndex(
                (b) =>
                  (item.build_id && b.id == item.build_id) ||
                  (item.extra && b.id == item.extra.build_id)
              );
              if (idx == -1) {
                build_bind.build.push({
                  id: item.build_id || (item.extra ? item.extra.build_id : 0),
                  build_number:
                    item.build_number ||
                    (item.extra ? item.extra.build_number : 0),
                  build_name:
                    item.build_name || (item.extra ? item.extra.build_name : 0),
                });
              }
              if (!build_bind.village) {
                build_bind.village = {
                  id:
                    item.village_id || (item.extra ? item.extra.village_id : 0),
                  name:
                    item.village_name ||
                    (item.extra ? item.extra.village_name : 0),
                  short_name:
                    item.village_short_name ||
                    (item.extra ? item.extra.village_short_name : 0),
                };
              }
            });
            // 是否跨楼宇选择了
            store.dispatch("SetMultiBuild", build_bind.build.length > 1);
            store.dispatch("SetCurrentBuildId", {
              buildIds: build_bind.build.map((it) => it.id),
              projectId: build_bind.village.id,
            });
            // console.log("basicinfo  form lease_square", lease_square);
            // console.log("basicinfo  form property_square", property_square);
            console.log("basicinfo  form build_bind", toRaw(build_bind));
            params.lease_square = lease_square;
            params.property_square = property_square;
            params.build_bind = build_bind;
            if (contractTagList.value.length) {
              params.contract_tag = [];
              contractTagList.value.forEach((item) => {
                if (item.checked) {
                  params.contract_tag.push(item.id);
                }
              });
              params.contract_tag = params.contract_tag.join(",");
            }
            // 非成本合同不需要传业主信息
            if (!isCostContract.value) {
              delete params.proprietor_info;
            }
            store.dispatch("SetAddFormData", {
              key: "basicInfo",
              data: params,
            });
            console.log("SetAddFormData basicInfo", params);
            context.emit("success", { key: "basicInfo" });
          });
          // context.emit("success", { key: "basicInfo" });
        })
        .catch(() => {
          context.emit("fail", { key: "basicInfo" });
        });
    };

    const changebranchid = () => {
      context.emit("branchid", state.formData.org_branch_id);
    }

    // 获取合同模板
    const templateList = ref([]);

    const getTemplateList = (callback) => {
      if (templateList.value.length) {
        callback && callback();
      } else {
        let params = { scene: "clause" };
        if (isRenewal.value || isChangeContract.value || isPurposeChangeContract.value) {
          delete params.scene;
        }
        request.get("/org", "/contract/termTemplate", params).then((res) => {
          templateList.value = res.list;
          callback && callback();
        });
      }
    };

    const getCompanyList = async () => {
      await request.post("/org", "/company/getDefaultBranchId", {}).then( async (data) => {
        let company_id = data?.org_branch_id;
        await request.get("/org", "/company/orgAndBranch", {}).then((res) => {
          state.companyList = res?.list || [];
          let index = (res?.list || []).findIndex((v) => v.id == company_id);
          if (index > -1) {
              const [removed] = res?.list.splice(index, 1);
              state.companyList.unshift(removed);
          }else{
            let systemIdIndex = (res?.list || []).findIndex((v) => v.is_system == 1);
            if (systemIdIndex > -1) {
              const [systemIdData] = res?.list.splice(systemIdIndex, 1);
              state.companyList.unshift(systemIdData);
            }
          }
          if(state.companyList.length ==1 ) {
            state.formData.org_branch_id = state.companyList[0].id
          }
          context.emit("branchid", state.formData.org_branch_id);
        });
      })
    };

    // 生成合同编号
    const currentTpl = ref(null);
    const handleTemplateSelect = (val, option) => {
      currentTpl.value = templateList.value.find((item) => item.id == val);
      //修改返回上一步切换模板
      state.showAllList = 0;
      store.dispatch("SetTplContent", {});
      state.validTime = {};
      //修改返回上一步切换模板

      if (option.scene == "clause") {
        // 自定义配置模板
        setAddFormByTemplate();
      } else {
        state.roomList = [];
        state.showSelectedHouse = false;
        setFormData({
          template_id: val,
        });
      }
      getContractNo();

      state.showHousingResources = false;
      if (option.scene == "CONTRACT_3" || option.scene == "clause") {
        /* 默认的物业合同模板 或者 自定义模板 优先使用 计费面积 */
        state.clauseType = "property";
      } else {
        state.clauseType = "lease";
      }
      nextTick(() => {
        state.showHousingResources = true;
      });
    };

    // 自定义模板内容回填
    const setAddFormByTemplate = () => {
      state.roomList = [];
      state.showSelectedHouse = false;
      request
        .get("/org", "/contract/clauseTemplate/detail", {
          id: currentTpl.value.id,
        })
        .then((res) => {
          const { data } = res;
          store.dispatch("SetTplContent", data);
          state.validTime = { ...data.basic_clause.validTime };
          delete data.basic_clause.validTime;
          setFormData({
            template_id: data.id,
            ...data.basic_clause,
            late_fee: data.latefee_clause,
            lease_endtime: getLeaseEndDay(),
          });
        });
      state.currentProjectBuild = currentTpl.value.relation_builds;
      console.log(
        "currentTpl.value.relation_builds===>",
        currentTpl.value.relation_builds
      );
      state.showAllList++;
    };
    const setFormData = (data) => {
      for (let key in data) {
        state.formData[key] = data[key];
      }
    };
    const getLeaseEndDay = () => {
      let date = state.formData.lease_endtime;
      let addNum = state.validTime.num || 1;
      let addUnit = state.validTime.num ? `${state.validTime.unit}s` : "years";
      if (
        (state.validTime && state.validTime.num) ||
        moment(state.formData.lease_starttime).isAfter(moment(date))
      ) {
        date = moment(state.formData.lease_starttime)
          .add(addNum, addUnit)
          .subtract(1, "days")
          .format(dateFormatStr);
      }
      return date;
    };

    const getContractNo = () => {
      request
        .get("/org", "/create/contract-no", {
          template_scene: currentTpl.value.scene,
          template_id: currentTpl.value.id,
          lease_starttime: state.formData.lease_starttime,
        })
        .then((res) => {
          state.formData.contract_number = res.no;
        });
    };

    const handleLeaseTimeChange = (val, type) => {
      if (
        type == "start" &&
        currentTpl.value &&
        currentTpl.value.scene == "clause" &&
        val &&
        isCopyContract.value
      ) {
        getContractNo();
      }
      if (
        moment(state.formData.lease_endtime).isBefore(
          moment(state.formData.lease_starttime)
        )
      ) {
        state.formData.lease_endtime = getLeaseEndDay();
      }
    };

    // 签订人是否可填
    watch(
      () => state.formData.owner_info.corporation,
      (val) => {
        if (val) {
          state.signatoryDisabled = false;
        } else if (!val && !state.formData.owner_info.signatory) {
          state.signatoryDisabled = true;
        }
      }
    );

    // 业主
    const proprietorList = ref([]);

    const getProprietorList = (roomList) => {
      const noCallBack = (msg = '') => {
        state.formData.proprietor_id = undefined;
        state.formData.proprietor_info.id = undefined;
        state.formData.proprietor_info.name = '';
        state.proprietorErrorMsg = msg;
      };
      if (roomList?.length) {
        state.chooseRoomLoading = true;
        request
          .post("/org", "/room/getOwnerByRoomIds", {
            room: roomList,
          })
          .then((res) => {
            let ownerInfoObj = res?.owner_info || {};
            if (!_.isEmpty(ownerInfoObj)) {
              state.proprietorErrorMsg = '';
              proprietorList.value = [
                {
                  value: ownerInfoObj.id,
                  label: ownerInfoObj.name,
                  ...ownerInfoObj,
                }
              ];
              state.formData.proprietor_id = ownerInfoObj.id;
              state.formData.proprietor_info.id = ownerInfoObj.id;
              state.formData.proprietor_info.name = ownerInfoObj.name;
              state.formData.proprietor_info.link_name = ownerInfoObj.link_name;
              state.formData.proprietor_info.phone = ownerInfoObj.phone;
              state.formData.proprietor_info.is_new = 1;
            } else if (res.msg) {
              noCallBack(res.msg);
              //失败
              notification.warning({
                message: '警告',
                description: res.msg
              });
            }
          }).catch((err) => {
          noCallBack();
        }).finally(() => {
          state.chooseRoomLoading = false;
        });
      } else {
        noCallBack();
      }
    };

    // 标签选择
    const handleTagCheck = ({ index, checked }) => {
      contractTagList.value[index].checked = checked;
    };

    // 添加标签
    const tagAddVisible = ref(false);
    const handleTagAddSuccess = () => {
      tagAddVisible.value = false;
      getContractTags();
    };

    const pageLoading = ref(true);
    // watch(pageLoading, (val) => {
    //   store.dispatch("SetAddPageLoading", val);
    // });
    // 获取表单下拉值
    const getInitOptions = () => {
      pageLoading.value = true;
      store.dispatch("ContractInit").then((res) => {
        state.optionData = res;
        pageLoading.value = false;
        if (store.getters.userInfo.uid) {
          state.formData.followup_uid = store.getters.userInfo.uid;
        } else {
          setDefaultValue(res.followup, "followup_uid", "uid");
        }
        setDefaultValue(
          res.calculate_accuracy_unit,
          "calculate_accuracy",
          "key"
        ); // 计算精度
        setDefaultValue(res.calculate_order_unit, "calculate_order", "key"); // 计算顺序
        if (res.lease_square_unit && res.lease_square_unit.length) {
          state.areaUnit = res.lease_square_unit[0].key;
          state.areaUnitName = res.lease_square_unit[0].name;
        }
      });
    };
    const setDefaultValue = (list, key, id) => {
      let { formData } = state;
      formData[key] = list && list.length ? list[0][id] : "";
    };

    // 获取合同标签
    const contractTagList = ref([]);
    const getContractTags = () => {
      return new Promise((resolve, reject) => {
        request.get("/org", "/manage/taglib/contract/all").then((res) => {
          contractTagList.value = res.list;
          resolve();
        });
      })
    };

    const editContractId = ref(0);
    const room_rent = ref({});
    const getDetail = () => {
      editContractId.value = Number(store.getters.editContractId);
      if (editContractId.value) {
        const { basicInfo } = store.getters.addFormData;
        let roomRent = {};
        if (includeSelfArea.value && basicInfo.room_rent) {
          // 当前合同当前租客已租
          if (
            basicInfo.room_rent.lease_square &&
            basicInfo.room_rent.lease_square.length
          ) {
            basicInfo.room_rent.lease_square.forEach((item) => {
              roomRent[item.id] = { lease: item.lease_area, property: 0 };
            });
          }
          if (
            basicInfo.room_rent.property_square &&
            basicInfo.room_rent.property_square.length
          ) {
            basicInfo.room_rent.property_square.forEach((item) => {
              roomRent[item.id] = {
                lease: roomRent[item.id] ? roomRent[item.id].lease : 0,
                property: item.lease_area,
              };
            });
          }
        }
        room_rent.value = roomRent;

        for (let key in basicInfo) {
          state.formData[key] = basicInfo[key];
        }

        state.roomList = basicInfo.build_bind.room;
        store.dispatch("SetCheckedRoomList", state.roomList);
        context.emit("changeroomList", state.roomList);
        store.dispatch(
          "SetMultiBuild",
          Array.isArray(basicInfo.build_bind.build) &&
            basicInfo.build_bind.build.length > 1
        );
        store.dispatch("SetCurrentBuildId", {
          buildIds: basicInfo.build_bind.build.map((it) => it.id),
          projectId: basicInfo.build_bind.village.id,
        });
        state.showSelectedHouse = true;

        // 默认选择模板
        getTemplateList(() => {
          currentTpl.value = templateList.value.find(
            (item) => item.id == basicInfo.template_id
          );

          if (currentTpl.value) {
            if (
              isRenewal.value ||
              isChangeContract.value ||
              isTransferNormal.value ||
              isPurposeChangeContract.value
            ) {
              // 变更、续租、转正时，重新获取合同编号
              getContractNo();
            } else if (currentTpl.value.scene == "clause") {
              // 复制或编辑合同时，选择的是自定义模板情况
              state.showSelectedHouse = false;
              state.currentProjectBuild = currentTpl.value.relation_builds;
              state.showAllList++;
              if (isCopyContract.value) {
                getContractNo();
              }
            }
          } else {
            // 如果 原来的模板已经失效,默认选择默认的租赁合同模板
            currentTpl.value = templateList.value.find(
              (item) => item.scene == "CONTRACT_4"
            );
            state.formData.template_id = currentTpl.value.id;
            // 重新获取合同编号
            getContractNo();
          }
          store.dispatch("SetInitClauseType", _.cloneDeep(currentTpl.value));
        });
      }
    };

    const setDraftDetail = (data) => {
      let basicInfo = data?.basicInfo || {};
      let roomList = data?.roomList || [];
      let tagListChecked = data?.contractTagListChecked || [];

      for (let key in basicInfo) {
        state.formData[key] = basicInfo[key];
      }
      state.roomList = roomList;
      store.dispatch("SetCheckedRoomList", state.roomList);
      context.emit("changeroomList", state.roomList);
      let buildIds = [];
      let villageId = 0;
      state.roomList.forEach((item) => {
        let build_id = item.build_id || (item.extra ? item.extra.build_id : 0);
        let village_id = item.village_id || (item.extra ? item.extra.village_id : 0);
        if (!villageId) {
          villageId = village_id;
        }
        if (buildIds.find((v) => v == build_id) < 0) {
          buildIds.push(build_id)
        }
      })
      store.dispatch(
        "SetMultiBuild",
        buildIds.length > 1
      );
      store.dispatch("SetCurrentBuildId", {
        buildIds: buildIds,
        projectId: villageId,
      });
      state.showSelectedHouse = !!state.roomList.length;
      if (basicInfo.template_id) {
        // 默认选择模板
        getTemplateList(() => {
          currentTpl.value = templateList.value.find(
            (item) => item.id == basicInfo.template_id
          );

          if (currentTpl.value) {
            if (currentTpl.value.scene == "clause") {
              // 复制或编辑合同时，选择的是自定义模板情况
              state.showSelectedHouse = false;
              state.currentProjectBuild = currentTpl.value.relation_builds;
              state.showAllList++;
            }
          } else {
            // 如果 原来的模板已经失效,默认选择默认的租赁合同模板
            currentTpl.value = templateList.value.find(
              (item) => item.scene == "CONTRACT_4"
            );
            state.formData.template_id = currentTpl.value.id;
            // 重新获取合同编号
            getContractNo();
          }
          store.dispatch("SetInitClauseType", _.cloneDeep(currentTpl.value));
        });
      }
      if (tagListChecked.length) {
        getContractTags().then(() => {
          contractTagList.value.forEach((item) => {
            if (tagListChecked.includes(item.id)) {
              item.checked = true;
            }
          });
        })
      }
    };

    // 合同上次选中
    watch([editContractId, contractTagList], ([id, list]) => {
      if (id && list.length) {
        const { basicInfo } = store.getters.addFormData;
        if (basicInfo.contract_tag.length) {
          list.forEach((item) => {
            if (basicInfo.contract_tag.includes(String(item.id))) {
              item.checked = true;
            }
          });
        }
      }
    });

    const getExtraField = () => {
      return new Promise((resolve, reject) => {
        request.get("/org", "/org/contract/extra/field/show").then((res) => {
          let lastArr = _.cloneDeep(state.formData.extra_field);
          state.formData.extra_field = (res?.list || []).map((v) => {
            let data = lastArr?.find((item) => item.name === v);
            return {
              name: v,
              value: data?.value || "",
            };
          });
          resolve();
        });
      });
    };

    const closeExtraManage = () => {
      getExtraField();
      state.extraManageVisible = false;
    };

    const Selectcancel = (id , data) => {
      state.formData.owner_id = id;
      state.formData.owner_info.owner_id = data.id;
      state.formData.owner_info.owner_name = data.name;
      state.formData.owner_info.industry_id = data.industry_id || undefined;
      state.formData.owner_info.signatory = data.contact_name || "";
      state.signatoryDisabled = !data.contact_name;
      state.formData.owner_info.corporation = data.business_info?.legalPerson || "";
    }

    const init = async () => {
      state.showAllList = 0;
      getTemplateList();
      await getInitOptions();
      await getContractTags();
      await getExtraField();
      await getCompanyList();
    };

    init().then(() => {
      state.defaultFinish = true;
    });

    watch(
      () => store.getters.editContractId,
      () => {
        getDetail();
      }
    );

    watch(
      () => store.getters.contractAddDraft,
      (val) => {
        if ((val?.basicInfo || val.roomList) && !$route.query.id) {
          // 新增时草稿有值时赋值
          setDraftDetail(val);
        }
      }
    );

    watch(
      () => store.getters.validateTrigger,
      (val) => {
        if (val) {
          const step = store.getters.currentStep;
          if (step == 0) {
            validateForm();
          }
        }
      }
    );

    const setDraftLocal = (key, data) => {
      if ($route.query.id) return;
      if (state.defaultFinish) {
        // 编辑了内容
        context.emit("onDefaultFinish", true);
      }
      let draftInfo = utils.getStorage("contract_draft_info");
      if (!draftInfo) {
        draftInfo = {};
      } else {
        draftInfo = JSON.parse(draftInfo);
      }
      draftInfo[key] = data;
      draftInfo.lastTime = utils.getDateString();
      utils.setStorage("contract_draft_info", JSON.stringify(draftInfo));
    };

    watch(
      () => state.formData,
      (val) => {
        setDraftLocal('basicInfo', _.cloneDeep(val))
      }, {deep: true}
    );

    watch(
      () => state.roomList,
      (val) => {
        setDraftLocal('roomList', _.cloneDeep(val))
      }, {deep: true}
    );

    watch(
      () => contractTagList.value,
      (val) => {
        let data = [];
        if (val?.length) {
          val.forEach((item) => {
            if (item?.checked) {
              data.push(item.id)
            }
          });
        }
        setDraftLocal('contractTagListChecked', _.cloneDeep(data))
      }, {deep: true}
    );
    const filterOption = (input, option) => {
      return option?.label?.toLowerCase()?.indexOf(input.toLowerCase()) >= 0;
    };

    let stateData = toRefs(state);


    return {
      isRenewal,
      ...stateData,
      dateFormatStr,
      disabledDate,
      pageLoading,
      validateInfos,
      templateList,
      contractTagList,
      tagAddVisible,
      handleTemplateSelect,
      handleTagCheck,
      handleTagAddSuccess,
      proprietorList,
      isCostContract,
      getRoomList,
      houseCardTitle,
      changeHouseCard,
      handleLeaseTimeChange,
      includeSelfArea,
      editContractId,
      room_rent,

      isPurposeContract,
      changeTreeLoading,
      closeExtraManage,
      filterOption,
      changebranchid,
      Selectcancel,
    };
  },
});
</script>
<style lang="less" scoped>
.icones{
  display: inline-block;
  height: 32px;
  line-height: 32px;
  width: 32px;
  text-align: center;
  color: #888787;
  cursor: pointer;
  border-top:1px solid #d9d9d9;
  border-right:1px solid #d9d9d9;
  border-bottom:1px solid #d9d9d9;
}
</style>